//
//  BKViewController+x.m
//  XPhoto
//
//  Created by baboy on 2019/2/20.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "UIViewController+version.h"
#import <BKKit/BKKit.h>
#import <BKKit/BKApi.h>
#import "AppVersion.h"
#import "HttpResponse.h"

@implementation UIViewController(version)
- (void)checkAppViersion{
    [BKApi checkVersionSuccess:^(id  _Nonnull task, id  _Nullable res) {
//        self.app = app;
        if (![res isSuccess]) {
            return;
        }
        AppVersion *appVer = [res data];
        NSString *msg = [appVer msg];
        NSMutableArray *btns = [NSMutableArray array];
        if ([appVer role] == AppUpdatePlicyUpdate) {
            [btns addObject:[NSNumber numberWithInteger:UIAlertActionStyleCancel]];
            [btns addObject:[NSNumber numberWithInteger:UIAlertActionStyleDefault]];
        }
        if ([appVer role] == AppUpdatePlicyForce || [appVer role] == AppUpdatePlicyExit) {
            [btns addObject:[NSNumber numberWithInteger:UIAlertActionStyleDefault]];
        }
        if ([btns count] > 0) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"update", @"提示")
                                                                           message:msg
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            for (int i = 0;i<[btns count] ; i++) {
                UIAlertActionStyle style = [[btns objectAtIndex:i] intValue];
                NSString *actionTitle = style == UIAlertActionStyleCancel ? NSLocalizedString(@"cancel", @"按钮") : NSLocalizedString(@"enter", @"按钮");
                UIAlertAction *action = [UIAlertAction actionWithTitle:actionTitle style:style handler:^(UIAlertAction * _Nonnull action) {
                    if (action.style == UIAlertActionStyleDefault && [appVer appStore]) {
                        [APP openURL:[NSURL URLWithString:[appVer appStore]] options:@{UIApplicationOpenURLOptionUniversalLinksOnly : @YES} completionHandler:^(BOOL success) {
                            
                        }];
                    }
                    if ([appVer role] == AppUpdatePlicyForce || [appVer role] == AppUpdatePlicyExit) {
                        exit(0);
                    }
                }];
                [alertController addAction:action];
            }
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
        }
    }
                     failure:^(id  _Nullable task, id  _Nullable json, NSError * _Nonnull error) {
                         
                     }];
}
@end
